<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://unpkg.com/@tailwindcss/browser@4"></script>
    <!-- <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> -->
    <script src="../../lib/jquery-3.5.1.min.js"></script>
    <script src="../../lib/axios.min.js"></script>
    <script type="module" src="../api/student.js"></script>
    <title>用户管理</title>
    <link rel="stylesheet" href="../../static/css/usermanage.css">
</head>

<body>
    <div class="container">
        <h1>用户管理</h1>
        <div class="form-group">
            <label for="searchInput">查找用户</label>
            <input type="text" id="searchInput" placeholder="输入姓名或邮箱">
            <button class="btn btn-primary" id="searchBtn">查找</button>
        </div>
        <button class="btn btn-primary" id="addUserBtn">添加用户</button>
        <table id="userTable">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>姓名</th>
                    <th>性别</th>
                    <th>邮箱</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- 数据将通过 JavaScript 动态添加 -->
            </tbody>
        </table>
        <div class="el-pagination" id="pagination"></div>
    </div>

    <!-- 添加用户模态框 -->
    <div id="addUserModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2>添加用户</h2>
            <form id="addUserForm">
                <div class="form-group">
                    <label for="addStuNo">学号</label>
                    <input type="text" id="addStuNo" required>
                </div>
                <div class="form-group">
                    <label for="addName">姓名</label>
                    <input type="text" id="addName" required>
                </div>
                <div class="form-group">
                    <label for="addStudSex">性别</label>
                    <input type="text" id="addStudSex" required>
                </div>
                <div class="form-group">
                    <label for="addEmail">邮箱</label>
                    <input type="email" id="addEmail" required>
                </div>
                <button type="submit" class="btn btn-primary">保存</button>
            </form>
        </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div id="editUserModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2>编辑用户</h2>
            <form id="editUserForm">
                <input type="hidden" id="editId">
                <div class="form-group">
                    <label for="editStudNo">学号</label>
                    <input type="text" id="editStudNo" required>
                </div>
                <div class="form-group">
                    <label for="editName">姓名</label>
                    <input type="text" id="editName" required>
                </div>
                <div class="form-group">
                    <label for="editStudSex">性别</label>
                    <input type="text" id="editSex" required>
                </div>
                <div class="form-group">
                    <label for="editEmail">邮箱</label>
                    <input type="email" id="editEmail" required>
                </div>
                <button type="submit" class="btn btn-primary">保存</button>
            </form>
        </div>
    </div>

    <!-- 消息提示元素 -->
    <div id="message" class="message"></div>

    <script type="module">
        import {selectall,addstud,editstud,deletestud,selectbyname} from "../api/student.js"
        $(document).ready(function () {
            // 请求数据
            select_by_page(currentPage)

        });

        // 模拟用户数据
        let users = [];
        let currentPage = 1;
        const itemsPerPage = 5;
        let edit_id = -1;
        var totalPages = -1

        function select_by_page(currentPage) {
            selectall(currentPage)
            .then(function(res) {
                if(res) {
                    // console.log(res)
                    users = res.data
                    // totalPages = res.count
                    totalPages = Math.ceil(res.count / itemsPerPage);
                    renderTable(users);
                }
                else {
                    console.log('没有数据')
                    return
                }
            })
        }

        
        // 渲染表格数据
        function renderTable(data) {
            // const startIndex = (currentPage - 1) * itemsPerPage;
            // const endIndex = startIndex + itemsPerPage;
            // const currentPageData = data.slice(startIndex, endIndex);

            $('#userTable tbody').empty();
            // currentPageData.forEach(user => {
                data.forEach(user => {
                $('#userTable tbody').append(`
                    <tr>
                        <td>${user.StudNo}</td>
                        <td>${user.StudName}</td>
                        <td>${user.StudSex}</td>
                        <td>${user.Email}</td>
                        <td>
                            <button class="btn btn-warning editBtn" data-id="${user.StudNo}">编辑</button>
                            <button class="btn btn-danger deleteBtn" data-id="${user.StudNo}">删除</button>
                        </td>
                    </tr>
                `);
            });
            renderPagination(data);
        }

        // 渲染分页
        function renderPagination(data) {
            // const totalPages = Math.ceil(res.count / itemsPerPage);
            // console.log(totalPages)
            $('#pagination').empty();

            const prevBtn = $('<span>').addClass('el-pagination__prev').html('<i class="fa-solid fa-chevron-left"></i>');
            if (currentPage === 1) {
                prevBtn.addClass('disabled');
            } else {
                prevBtn.click(function () {
                    currentPage--;
                    select_by_page(currentPage)
                    console.log(users)
                    renderTable(data);
                });
            }
            $('#pagination').append(prevBtn);

            const maxVisiblePages = 5;
            let startPage = Math.max(currentPage - Math.floor(maxVisiblePages / 2), 1);
            let endPage = startPage + maxVisiblePages - 1;
            if (endPage > totalPages) {
                endPage = totalPages;
                startPage = Math.max(endPage - maxVisiblePages + 1, 1);
            }

            for (let i = startPage; i <= endPage; i++) {
                const pageItem = $('<span>').addClass('el-pagination__item').text(i);
                if (i === currentPage) {
                    pageItem.addClass('active');
                }
                pageItem.click(function () {
                    currentPage = i;
                    select_by_page(currentPage)
                    renderTable(data);
                });
                $('#pagination').append(pageItem);
            }

            const nextBtn = $('<span>').addClass('el-pagination__next').html('<i class="fa-solid fa-chevron-right"></i>');
            if (currentPage === totalPages) {
                nextBtn.addClass('disabled');
            } else {
                nextBtn.click(function () {
                    currentPage++;
                    select_by_page(currentPage)
                    renderTable(data);
                });
            }
            $('#pagination').append(nextBtn);
        }

        // 显示消息提示
        function showMessage(message, type) {
            const $message = $('#message');
            $message.removeClass('message-success message-error').addClass(`message-${type}`).text(message);
            $message.css('opacity', 1);
            setTimeout(() => {
                $message.css('opacity', 0);
            }, 3000);
        }

        // 初始渲染
        // renderTable(users);

        // 显示添加用户模态框
        $('#addUserBtn').click(function () {
            $('#addUserModal').show();
        });

        // 关闭模态框
        $('.close').click(function () {
            $('.modal').hide();
        });

        // 添加用户
        $('#addUserForm').submit(function (e) {
            // addstud
            e.preventDefault();
            const stuno = $('#addStuNo').val();
            const name = $('#addName').val();
            const sex = $('#addStudSex').val();
            const email = $('#addEmail').val();

            // const newId = users.length > 0 ? users[users.length - 1].id + 1 : 1;
            const newUser = {
                "studno":stuno,
                "studname":name,
                "studsex":sex,
                "email":email
            };
            const adduser = {
                "StudNo":stuno,
                "StudName":name,
                "StudSex":sex,
                "Email":email
            }
            addstud(newUser)
            .then(function(res) {
                if(res.status == "true") {
                    
                    users.push(adduser);
                    renderTable(users);
                    $('#addUserModal').hide();
                    $('#addUserForm')[0].reset();
                    showMessage('添加用户成功', 'success');
                }
                else {
                    showMessage('学号已存在，请重新输入', 'error');
                }
            })

        });

        // 编辑用户
        $('#userTable').on('click', '.editBtn', function () {
            // editstud
            const id = $(this).data('id');
            edit_id = id
            // console.log("editid:",id)
            const user = users.find(u => u.StudNo === id);
            // console.log("edit:",users)
            $('#editStudNo').val(user.StudNo);
            $('#editName').val(user.StudName);
            $('#editSex').val(user.StudSex);
            $('#editEmail').val(user.Email);
            $('#editUserModal').show();
        });

        $('#editUserForm').submit(function (e) {
            e.preventDefault();
            // const id = parseInt($('#editId').val());
            // const id = parseInt($(this).data('id'));
            // console.log("editid:",edit_id)
            const name = $('#editName').val();
            const sex = $('#editSex').val();
            const email = $('#editEmail').val();
            const stud = {
                "studname":name,
                "studsex":sex,
                "email":email
            }
            const index = users.findIndex(u => u.StudNo === edit_id);
            // console.log("index:",index)
            if (index!== -1) {
                users[index].StudNo = edit_id;
                users[index].StudName = name;
                users[index].Email = email;
                users[index].StudSex = sex;
                renderTable(users);
                // console.log(users)
                $('#editUserModal').hide();
                $('#editUserForm')[0].reset();
                editstud(stud)
                .then(function(res) {
                    if(res.status == "true") {
                        showMessage('编辑用户成功', 'success');
                    }
                    else {
                        showMessage('编辑用户失败，未找到该用户', 'error');
                    }
                })
                
            } else {
                showMessage('编辑用户失败，未找到该用户', 'error');
            }
        });

        // 删除用户
        $('#userTable').on('click', '.deleteBtn', function () {
            // alert("确认删除")
            const isConfirmed = confirm("确认删除");
            if (!isConfirmed) {
                return;
            }
            // deletestud
            const id = $(this).data('id');
            // console.log("delete:",id)
            const newUsers = users.filter(u => u.StudNo!== id);

            if (newUsers.length!== users.length) {
                users = newUsers;
                renderTable(users);
                deletestud(id)
                .then(function(res) {
                        // console.log(res)
                        if(res.status == "true") {
                            showMessage('删除用户成功', 'success');
                        }
                        else {
                            showMessage('删除用户失败，未找到该用户', 'error');
                        }
                    })
            } else {
                showMessage('删除用户失败，未找到该用户', 'error');
            }
        });

        // 查找用户
        $('#searchBtn').click(function () {
            const keyword = $('#searchInput').val().trim();
            if (keyword === '') {
                currentPage = 1;
                renderTable(users);
                // console.log("yes")
                return;
            }
            // const searchResults = users.filter(user => {
            //     return user.StudName.includes(keyword) || user.Email.includes(keyword);
            // });
            selectbyname(keyword)
            .then(function(res) {
                if(res.status == "true") {
                    var studinfo = res.data
                    showMessage('查找用户成功', 'success');
                    currentPage = 1;
                    // var users = []
                    users = []
                    users.push(studinfo)
                    renderTable(users);
                }
                else {
                    showMessage('未找到相关用户', 'error');
                }
            })
            // if (searchResults.length === 0) {
            //     showMessage('未找到相关用户', 'error');
            // } else {
            //     currentPage = 1;
            //     renderTable(searchResults);
            // }
        });
        
    </script>
</body>

</html>